import Vue from 'vue';
import ViewUI from '_c/iview/index';
import Util from '../libs/util';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import {routers} from './router';
import store from '../store';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
    mode: process.env.NODE_ENV === 'production' ? 'history' : 'hash',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

const checkAndGo = (to, from, next) => {
    ViewUI.LoadingBar.start();
    Util.title(to.meta.title);
    let token = store.getters.access_token;
    let time = (store.getters.expires_in-(Date.now))/1000;
    let tenantId = store.getters.tenantId;
    let login = Util.checkLogin(token,time);
    if (Cookies.get('locking') === '1' && to.name !== 'locking') {
        // 判断当前是否是锁定状态
        if(!login){
            Cookies.set('locking','0')
            if (tenantId) {
                next({
                    path: '/' + tenantId + '/login'
                });
            } else {
                next({
                    path: '/system/login'
                });
            }
        }else {
            next({
                replace: true,
                name: 'locking'
            });
        }
    } else if (Cookies.get('locking') === '0' && to.name === 'locking') {
        next(false);
    } else {
        // 白名单
        if (!login && to.name !== 'login') {
            if (tenantId) {
                next({
                    path: '/' + tenantId + '/login'
                });
            } else {
                next({
                    path: '/system/login'
                });
            }

        } else if (login && to.name === 'login') {
            // 判断是否已经登录且前往的是登录页
            Util.title();
            next({
                name: 'home_index'
            });
        } else {
            // 有url属性则打开
            Util.toDefaultPage([...routers], to.name, router, next);
        }
    }
}

//设置路由守卫 手工跳转404
router.beforeEach((to, from, next) => {
    if (to.name == 'afsLink'||to.name == 'sso') {
        next();
    } else {
        if (to.matched.length !== 0) {
            checkAndGo(to, from, next);
        } else {
            //还未从后台加载菜单 直接进行判断处理
            if (store.getters.menuList.length > 0) {
                next({name: 'sub-404'})
            } else {
                checkAndGo(to, from, next);
            }
        }
    }
});

router.afterEach((to) => {
    ViewUI.LoadingBar.finish();
});
